import os
import time
import json
import threading
import traceback

import wmi
import urllib3
import win32con
import pythoncom
from PIL import ImageGrab

from py.start_common import common_init
from py.storage.SettingUtil import setting
from py.uitls import WinUtil
from py.uitls.PyUtil import is_none


def screen():
    screen_file = None
    e1 = None
    e2 = None
    e3 = None

    try:
        screen_file = screen01()
    except:
        e1 = "screen01:\n" + traceback.format_exc()

    if screen_file is not None:
        return screen_file

    # 第1个截屏方式失败，则使用第二种截屏方式
    try:
        screen_file = screen02()
    except:
        e2 = "screen02:\n" + traceback.format_exc()

    if screen_file is not None:
        return screen_file

    # 截屏失败，同时抛出两个错误信息
    e1_str = is_none(e1, "screen01：没有错误信息")
    e2_str = is_none(e2, "screen02：没有错误信息")
    e3_str = is_none(e3, "screen03：没有错误信息")

    raise Exception("\n" + e1_str + "\n" + e2_str + "\n\n" + e3_str)


def screen01():
    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    pic_name = os.path.join(setting.file_path, now_time + '-01.png')

    pic = ImageGrab.grab()
    pic.save(pic_name)
    return pic_name


def screen02():
    # 使用异步的方式按键，防止被阻塞
    threading.Thread(target=WinUtil.click_key, args=(win32con.VK_SNAPSHOT, 0)).start()
    time.sleep(0.1)
    threading.Thread(target=WinUtil.click_key, args=(win32con.VK_MENU, 0)).start()
    time.sleep(0.1)

    threading.Thread(target=WinUtil.click_key, args=(win32con.VK_SNAPSHOT, win32con.KEYEVENTF_KEYUP)).start()
    time.sleep(0.1)
    threading.Thread(target=WinUtil.click_key, args=(win32con.VK_MENU, win32con.KEYEVENTF_KEYUP)).start()
    time.sleep(0.5)

    now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    pic_name = os.path.join(setting.file_path, now_time + '-02.png')

    im = ImageGrab.grabclipboard()
    if im is not None:
        im.save(pic_name)
        return pic_name


def device_info():
    # 子线程中必须初始化pythoncom
    pythoncom.CoInitialize()
    wmi_wmi = wmi.WMI()
    info_list = []
    for BIOSs in wmi_wmi.Win32_ComputerSystem():
        info_list.append("电脑名称: %s" % BIOSs.Caption)
        info_list.append("使 用 者: %s" % BIOSs.UserName)
    for address in wmi_wmi.Win32_NetworkAdapterConfiguration(ServiceName="e1dexpress"):
        info_list.append("IP地址: %s" % address.IPAddress[0])
        info_list.append("MAC地址: %s" % address.MACAddress)
    for BIOS in wmi_wmi.Win32_BIOS():
        info_list.append("使用日期: %s" % BIOS.Description)
        info_list.append("主板型号: %s" % BIOS.SerialNumber)
    for processor in wmi_wmi.Win32_Processor():
        info_list.append("CPU型号: %s" % processor.Name.strip())
    for memModule in wmi_wmi.Win32_PhysicalMemory():
        total_mem_size = int(memModule.Capacity)
        info_list.append("内存厂商: %s" % memModule.Manufacturer)
        info_list.append("内存型号: %s" % memModule.PartNumber)
        info_list.append("内存大小: %.2fGB" % (total_mem_size / 1024 ** 3))
    for disk in wmi_wmi.Win32_DiskDrive(InterfaceType="IDE"):
        disk_size = int(disk.size)
        info_list.append("磁盘名称: %s" % disk.Caption)
        info_list.append("磁盘大小: %.2fGB" % (disk_size / 1024 ** 3))
    for xk in wmi_wmi.Win32_VideoController():
        info_list.append("显卡名称: %s" % xk.name)
    return info_list


def ip_info():
    http = urllib3.PoolManager()
    url = "http://pv.sohu.com/cityjson?ie=utf-8"
    response = http.request('GET', url)
    text = response.data
    jsonStr = text[text.find(b"{"):text.rfind(b"}") + 1]
    jsonObj = json.loads(jsonStr)
    return jsonObj


if __name__ == '__main__':
    common_init()
